<template>
  <v-container fluid tag="section">
    <v-row>
      <v-col sm="12" md="12">
        <v-card icon="mdi-clipboard-text" class="px-md-5 py-md-3 pa-xs-0 mt-0">
          <v-card-title>
            <v-row>
              <v-col cols="12" sm="12" md="3">
                <v-text-field
                  v-model="search.keyword"
                  label="关键词"
                ></v-text-field>
              </v-col>
              <v-col cols="12" sm="12" md="3">
                <v-select
                  v-model="search.type"
                  :items="dataDicts.noticeTypeDicts"
                  item-text="value"
                  item-value="code"
                  label="类型"
                ></v-select>
              </v-col>
              <v-col cols="12" sm="12" md="6" class="text-left">
                <v-btn
                  regular
                  color="primary"
                  @click="dataInitialize()"
                  class="mr-2"
                >
                  查 询
                </v-btn>
                <v-btn
                  regular
                  color="warning"
                  @click="clearChanged()"
                  class="ml-2"
                >
                  重 置
                </v-btn>
              </v-col>
            </v-row>
          </v-card-title>
          <v-card-text>
            <v-data-table
              v-model="selectedTableItems"
              :no-data-text="noDataText"
              :show-select="showSelect"
              :single-select="singleSelect"
              :dense="dense"
              :headers="headers"
              :items="records"
              :options.sync="options"
              :multi-sort="multiSort"
              :server-items-length="total"
              :loading="loading"
              :item-key="itemKey"
              :loading-text="loadingText"
              :footer-props="footerProps"
              @update:options="dataInitialize()"
            >
              <template v-slot:top>
                <v-toolbar flat>
                  <v-toolbar-title class="d-none d-sm-flex">
                    {{ tableTitle }}
                  </v-toolbar-title>
                  <v-divider
                    class="mx-4 d-none d-sm-flex"
                    inset
                    vertical
                  ></v-divider>
                  <v-spacer></v-spacer>
                  <v-btn color="primary" dark @click="remove(-1)" class="mr-2">
                    批量删除
                  </v-btn>
                  <v-dialog
                    v-model="dialog"
                    persistent
                    max-width="1000px"
                    :retain-focus="retainFocus"
                  >
                    <v-card>
                      <v-card-title class="text-left">
                        <span class="text-h3 font-weight-black text-left">
                          详情
                        </span>
                      </v-card-title>
                      <v-divider></v-divider>
                      <v-card-text class="pt-4">
                        <v-form ref="form">
                          <v-row>
                            <v-col cols="12" class="pb-0">
                              <div class="text-h4 font-weight-bold">标题</div>
                              <v-text-field
                                v-model="editedItem.title"
                                :autofocus="false"
                                dense
                              ></v-text-field>
                            </v-col>
                            <v-col cols="12" class="pb-0">
                              <div class="text-h4 font-weight-bold">类型</div>
                              <v-radio-group
                                v-model="editedItem.type"
                                row
                                dense
                                class="mt-2"
                                :rules="[(v) => !!v || '该项为必填项！']"
                              >
                                <v-radio
                                  v-for="(
                                    item, index
                                  ) in dataDicts.noticeTypeDicts"
                                  :key="index"
                                  :value="item.code"
                                  :label="item.value"
                                ></v-radio>
                              </v-radio-group>
                            </v-col>
                            <v-col cols="12" class="pb-0">
                              <div class="text-h4 font-weight-bold">内容</div>
                              <tinymce-editor
                                ref="editor"
                                v-model="editedItem.content"
                              />
                            </v-col>
                          </v-row>
                        </v-form>
                      </v-card-text>
                      <v-card-actions>
                        <v-spacer></v-spacer>
                        <v-btn text @click="close()" color="darken-1">
                          关闭
                        </v-btn>
                      </v-card-actions>
                    </v-card>
                  </v-dialog>
                </v-toolbar>
              </template>

              <template v-slot:[`item.type`]="{ item }">
                {{ noticeTypeFilter(item.type) }}
              </template>
              <template v-slot:[`item.status`]="{ item }">
                {{ noticeStatusFilter(item.status) }}
              </template>
              <template v-slot:[`item.actions`]="{ item }">
                <v-icon
                  small
                  @click="detailsItem(item)"
                  title="修改"
                  class="mr-2"
                >
                  mdi-pencil
                </v-icon>
                <v-icon small @click="remove(item)" title="删除">
                  mdi-delete
                </v-icon>
              </template>
              <template v-slot:no-data>
                <v-btn small color="primary" @click="dataInitialize()">
                  刷新
                </v-btn>
              </template>
            </v-data-table>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "ReceivedNoticeIndex",
  data: () => ({
    dense: false, //是否紧凑（降低行高）
    noDataText: "暂无任何数据", //没有数据时显示的内容
    loading: true, //开启加载条
    loadingText: "数据加载中...请稍候！", //加载条内容
    footerProps: {
      "items-per-page-options": [10, 20, 50, 100], //自定义每页行数的下拉框  -1 代表全部
      "items-per-page-text": "每页行数",
      //"items-per-page-all-text": "全部",
    },
    multiSort: true, //多列排序
    records: [], //数据
    total: 0, //数据总条数
    showSelect: true, //将在默认表头中渲染一个复选框以切换所有行是否被选择，同时也为每个默认行渲染一个复选
    singleSelect: false, //指定能同时选择多行还是只能选择一行

    //日期时间组件相关
    dateModal: false,
    itemKey: "id", //行项需要一个唯一的键属性才能展开。 默认值是id，但是你可以使用item-key prop来指定一个不同的item属性。
    tableTitle: "已读公告列表",
    //查询条件
    search: {
      keyword: "",
      type: 0,
    },
    options: {
      page: 1, //当前页码
      itemsPerPage: 10, //每页多少条
      pageStart: 1, //起始页码
      pageStop: 1, //终止页码
      sortBy: ["publicTime", "title"], //排序列
      sortDesc: [false, false], //排序列是否倒叙
    },
    headers: [
      {
        text: "序号", //标头
        align: "start", //所在位置
        sortable: false, //排序方式
        value: "id", //数据对应的字段名
      },
      { text: "标题", value: "title" },
      { text: "类型", sortable: false, value: "type" },
      { text: "状态", sortable: false, value: "status" },
      { text: "发布时间", value: "publicTime" },
      { text: "发布人", sortable: false, value: "publicUserName" },
      { text: "操作", value: "actions", sortable: false },
    ],
    selectedTableItems: [], //选中的表格项
    // 表格弹框相关
    retainFocus: false, // 默认情况下，制表符焦点将返回到对话框的第一个子级。在使用需要焦点的外部工具（如 TinyMCE 或 vue-clipboard）时禁用此选项。
    dialog: false,
    editedItem: {
      id: 0,
      title: "",
      content: "",
      type: "",
      publicUserId: 0,
      publicUserName: "",
      publicOrgId: 0,
      publicOrgName: "",
      publicTime: "",
      cancelTime: "",
      status: "",
      noticeId: 0,
      userId: 0,
      readTime: "",
      readStatus: 0,
    },
    defaultItem: {
      id: 0,
      title: "",
      content: "",
      type: "",
      publicUserId: 0,
      publicUserName: "",
      publicOrgId: 0,
      publicOrgName: "",
      publicTime: "",
      cancelTime: "",
      status: "",
      noticeId: 0,
      userId: 0,
      readTime: "",
      readStatus: 0,
    },
    dataDicts: {
      noticeTypeDicts: [],
      noticeStatusDicts: [],
    },
  }),
  created() {
    this.setDictDatas();
  },
  methods: {
    /**
     * 清空查询条件
     */
    clearChanged() {
      this.search.keyword = "";
      this.search.type = "";
    },
    /**
     * 数据初始化
     */
    dataInitialize() {
      var that = this;
      that.loading = true;
      that.request
        .post("/api/notice/receivedPage", {
          page: that.options.page,
          itemsPerPage: that.options.itemsPerPage,
          sortBy: that.options.sortBy,
          sortDesc: that.options.sortDesc,
          // 查询条件
          keyword: that.search.keyword,
          type: that.search.type,
        })
        .then((res) => {
          that.records = res.data.records;
          that.total = res.data.total;
          that.loading = false;
        })
        .catch((error) => {
          console.log(error);
          that.loading = false;
        });
    },
    /**
     * 数据删除
     */
    dataDelete(ids) {
      var that = this;
      that.request.post("/api/noticeUser/removeBatchByIds", ids).then((res) => {
        that.$dialog.notify.success("删除成功！", {
          timeout: 2000,
        });
        setTimeout(() => {
          that.dataInitialize();
        }, 2000);
      });
    },
    /**
     * 设置字典数据
     */
    setDictDatas(text) {
      var that = this;
      that.request
        .get("/api/dictType/dropDown", {
          code: "notice_type",
        })
        .then((res) => {
          that.dataDicts.noticeTypeDicts = res.data;
        });
      that.request
        .get("/api/dictType/dropDown", {
          code: "notice_status",
        })
        .then((res) => {
          that.dataDicts.noticeStatusDicts = res.data;
        });
    },
    /**
     * 通知类型过滤
     */
    noticeTypeFilter(noticeType) {
      const values = this.dataDicts.noticeTypeDicts.filter(
        (item) => item.code == noticeType
      );
      if (values.length > 0) {
        return values[0].value;
      }
    },
    /**
     * 通知状态过滤
     */
    noticeStatusFilter(noticeStatus) {
      const values = this.dataDicts.noticeStatusDicts.filter(
        (item) => item.code == noticeStatus
      );
      if (values.length > 0) {
        return values[0].value;
      }
    },
    /**
     * 删除项
     */
    remove(dataItem) {
      var that = this,
        ids = [];
      if (dataItem == -1) {
        // 批量删除
        var items = that.selectedTableItems;
        if (items == undefined || items == null || items.length == 0) {
          this.$dialog.notify.warning("请选择要删除的数据项！", {
            position: "top-right",
            timeout: 3000,
          });
          return;
        }
        ids = items.map((item) => {
          return item.id;
        });
      } else {
        ids.push(dataItem.id);
      }
      that.$dialog.confirm({
        text: "确定要删除该项数据吗?",
        title: "警告",
        icon: "mdi-alert-circle",
        actions: [
          {
            text: "取消",
            key: false,
          },
          {
            text: "确定",
            color: "primary",
            key: true,
            handler: function () {
              that.dataDelete(ids);
            },
          },
        ],
      });
    },
    /**
     * 修改项
     */
    detailsItem(item) {
      this.editedItem = Object.assign({}, item);
      this.editedItem.type = this.editedItem.type.toString();
      this.dialog = true;
    },
    /**
     * 关闭编辑弹框
     */
    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
      });
    },
  },
  watch: {
    dialog(val) {
      val || this.close();
    },
  },
};
</script>
